package handler

import (
	"2302a/weekly/api/request"
	"2302a/weekly/api/resp"
	"2302a/weekly/consts"
	"2302a/weekly/internal/dao"
	"2302a/weekly/internal/model"
	"2302a/weekly/pkg"
	"github.com/gin-gonic/gin"
	"time"
)

func UserRegister(c *gin.Context) {
	var req request.UserRegisterReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 10000, "参数信息错误", err.Error())
		return
	}
	var user model.User
	dao.GetMobileByFinds(&model.User{Mobile: req.Mobile}, &user)
	if user.Id > 0 {
		resp.Error(c, 10000, "用户已存在", false)
		return
	}
	create := model.User{
		Mobile:    req.Mobile,
		Password:  pkg.GetEncryption(req.Password),
		Nickname:  req.Nickname,
		Profile:   req.Profile,
		Signature: req.Signature,
		Gender:    req.Gender,
	}
	dao.Create(&create)
	if pkg.GetEncryption(req.Password) != pkg.GetEncryption(req.Confirm) {
		resp.Error(c, 10000, "两个密码不一致", false)
		return
	}
	resp.Success(c, "注册成功", true)
}

func UserLogin(c *gin.Context) {
	var req request.UserLoginReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 10000, "参数信息错误", err.Error())
		return
	}
	var user model.User
	dao.GetMobileByFinds(&model.User{Mobile: req.Mobile}, &user)
	if user.Id == 0 && pkg.GetEncryption(req.Password) != pkg.GetEncryption(req.Confirm) {
		resp.Error(c, 10000, "账号或者密码错误", false)
		return
	}
	token := pkg.CreateJwtToken(user.Id, 24*time.Hour, consts.JWT_KEY)
	resp.Success(c, "登录成功", token)
}
